package com.test.platform.service.user;

import com.test.platform.dao.UserMapper;
import com.test.platform.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.UUID;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Transactional
    public User register(String username, String password, String email) {
        // 检查用户名是否已存在
        if (userMapper.findByUsername(username) != null) {
            throw new RuntimeException("用户名已存在");
        }

        User user = new User();
        user.setUsername(username);
        user.setSalt(UUID.randomUUID().toString());
        // 使用 Spring Security 的密码加密
        user.setPassword(passwordEncoder.encode(password));
        user.setEmail(email);
        user.setCreateTime(LocalDateTime.now());
        user.setEnabled(true);
        user.setRole("ROLE_USER");  // 默认角色

        userMapper.insert(user);
        return user;
    }

    public User findByUsername(String username) {
        return userMapper.findByUsername(username);
    }

    @Transactional
    public void updateLastLoginTime(User user) {
        user.setLastLoginTime(LocalDateTime.now());
        userMapper.updateLastLoginTime(user);
    }
}